import * as THREE from 'three';
import { TweenMax } from "gsap";

const pool = [];

// 创建破碎特效碎片
class Particle {
	constructor() {
		this.mesh = null; // 实例

		this.draw()
	}

	explode(pos, color, scale) {
		const _this = this;
		const _p = this.mesh.parent;
		this.mesh.material.color = new THREE.Color(color);
		this.mesh.material.needsUpdate = true;
		this.mesh.scale.set(scale, scale, scale);
		const targetX = pos.x + (-1 + Math.random() * 2) * 50;
		const targetY = pos.y + (-1 + Math.random() * 2) * 50;
		const speed = .6 + Math.random() * .2;
		TweenMax.to(this.mesh.rotation, speed, { x: Math.random() * 12, y: Math.random() * 12 });
		TweenMax.to(this.mesh.scale, speed, { x: .1, y: .1, z: .1 });
		TweenMax.to(this.mesh.position, speed, {
			x: targetX, y: targetY, delay: Math.random() * .1, ease: '', onComplete: function () {
				if (_p) _p.remove(_this.mesh);
				_this.mesh.scale.set(1, 1, 1);
				pool.unshift(_this);
			}
		});
	}

	draw() {
		const geom = new THREE.TetrahedronGeometry(3, 0);
		const mat = new THREE.MeshPhongMaterial({
			color: 0x009999,
			shininess: 0,
			specular: 0xffffff,
			shading: THREE.FlatShading
		});
		this.mesh = new THREE.Mesh(geom, mat);
	}
}

// 破碎特效（吃硬币或撞石头）
export default class ParticlesHolder {
	constructor(n = 10) {
		this.mesh = new THREE.Object3D(); // 实例
		for (let i = 0; i < n; i++) { pool.push(new Particle()) }; // 创建的所有破碎特效
	}

	// 添加特效
	spawnParticles(pos, density, color, scale) {
		for (let i = 0; i < density; i++) {
			const particle = pool.length
				? pool.pop() // 储存池中有破碎特效
				: new Particle(); // 新建破碎特效实例

			this.mesh.add(particle.mesh);
			particle.mesh.visible = true;
			particle.mesh.position.y = pos.y;
			particle.mesh.position.x = pos.x;
			particle.explode(pos, color, scale);
		}
	}
}